"""
异常统一处理模块
"""
import logging

from flask import (jsonify)

from app.web import manage
from app.common.exception import (InvalidParamException, InvalidSignException, InvalidUserException,
                                  UnauthorizedException, AccessLimitationException)


@manage.app_errorhandler(500)
def error_500(e):
    """
    500异常处理
    :return:
    """
    logging.error(e)
    result = dict(code=5000, msg="服务器内部异常")
    return jsonify(result)


@manage.app_errorhandler(404)
def error_404(e):
    """
    404异常处理
    :return:
    """
    logging.error(e)
    result = dict(code=4040, msg="资源不存在")
    return jsonify(result)


@manage.errorhandler(Exception)
def hand_errors(e):
    """
    统一处理错误异常
    :param e:
    :return:
    """

    logging.error(e)
    msg = str(e)

    if isinstance(e, InvalidParamException):
        result = dict(code=3010, msg=msg)
        return jsonify(result)
    elif isinstance(e, InvalidSignException):
        result = dict(code=1010, msg=msg)
        return jsonify(result)
    elif isinstance(e, InvalidUserException):
        result = dict(code=2010, msg=msg)
        return jsonify(result)
    elif isinstance(e, UnauthorizedException):
        result = dict(code=1011, msg=msg)
        return jsonify(result)
    elif isinstance(e, AccessLimitationException):
        result = dict(code=4010, msg=msg)
        return jsonify(result)
    else:
        result = dict(code=5000, msg="服务器内部异常")
        return jsonify(result)
